package com.xgp.Software.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xgp.Software.dto.AccessTokenDTO;
import com.xgp.Software.dto.GithubUser;
import jdk.nashorn.internal.parser.Token;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component//将当前类初始到容器的上下文
public class GithubProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
//                .url("https://github.com/login/oauth/authorize")
//                .url("https://github.com/login/oauth/access_token")
                .url("https://gitee.com/oauth/token?grant_type=authorization_code")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
//            System.out.println("string = " + string);
            String[] split = string.split(",");
            String tokenstr = split[0];
//            System.out.println("tokenstr = " + tokenstr);
            String token = tokenstr.split(":")[1];
//            System.out.println("token = " + token);

//            System.out.println(string);
            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public GithubUser githubUser(String accessToken) {
        String url = "https://gitee.com/api/v5/user?access_token="+accessToken;
//        System.out.println(accessToken);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
//                .url("https://api.github.com/user?access_token="+accessToken)
                .url(url.replaceAll("\"",""))
                .build();
        try {
            Response response = client.newCall(request).execute();
//            System.out.println("response = " + response);
            String string = response.body().string();
//            System.out.println("string2 = " + string);
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
//            System.out.println("githubUser = " + githubUser);
            return githubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
